import { defineStore } from 'pinia';
import { login, logout, getInfo, adminLogin, smsLogin, getInfoOfApp } from '@/api/login';
import { getToken, setToken, removeToken, setUserLoginType, getUserLoginType } from '@/utils/auth';
import { unref } from 'vue';
import { awaitWrap } from '@/utils';

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    name: '',
    userId: '',
    avatar: '',
    roles: [],
    permissions: [],
  }),
  actions: {
    // 登录
    login(userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            setToken(res.token);
            this.token = res.token;
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 系统管理员登录
    adminLogin(userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        adminLogin(username, password, code, uuid)
          .then((res) => {
            setUserLoginType('sys');
            setToken(res.data.token);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 短信验证码登录
    smsLogin(argumentUserInfo) {
      const userInfo = unref(argumentUserInfo);
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        smsLogin(username, password, code, uuid)
          .then((res) => {
            console.log(res);
            setToken(res.token);
            setUserLoginType('sys');
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise(async (resolve, reject) => {
        // 初始化res，nil
        let res,
          nil = null;

        if (getUserLoginType() === 'sys') {
          [res, nil] = await awaitWrap(getInfo());
        } else {
          [res, nil] = await awaitWrap(getInfoOfApp());
        }
        // 错误处理
        nil !== null && reject(nil);
        // 设置基本数据
        const user = res.user;
        if (res.roles && res.roles.length > 0) {
          this.roles = res.roles;
          this.permissions = res.permissions;
        } else {
          this.roles = ['ROLE_DEFAULT'];
        }
        this.userId = user.userId;
        this.name = user.userName;
        resolve(res);
      });
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        logout(this.token)
          .then(() => {
            this.token = '';
            this.roles = [];
            this.permissions = [];
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
});

export default useUserStore;
